package com.ytzl.gotrip.controller;

import com.ytzl.gotrip.model.GotripUser;
import com.ytzl.gotrip.service.GotripUserService;
import com.ytzl.gotrip.service.LoginService;
import com.ytzl.gotrip.utils.common.Constants;
import com.ytzl.gotrip.utils.common.Dto;
import com.ytzl.gotrip.utils.common.DtoUtil;
import com.ytzl.gotrip.vo.ItripTokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;

/**
 * 用户登录
 */
@RestController
@Api(description ="登录注销控制器")
@RequestMapping("/api")
public class LoginController {
    @Resource
    private GotripUserService gotripUserService;
    @Resource
    private LoginService loginService;
    /**
     *
     * @param name
     * @param password
     * @return
     */
    @ApiOperation(value ="登录")
    @PostMapping("/dologin")
    public Dto doLogin(
            @ApiParam(value = "登录账号") @RequestParam("name") String name,
            @ApiParam(value = "登录密码") @RequestParam("password")String password,
            @ApiParam(hidden = true)@RequestHeader(value = "user-agent",required = false) String userAgent) throws Exception {
            //required =false 如果为true RequestHeader 系统默认添加 swagger会判断有值未填写不让提交
            //hidden = true 隐藏隐形传递
        //查询用户信息
        GotripUser gotripUser=gotripUserService.findByUserCode(name);
        //用户登录
        String token = loginService.doLogin(gotripUser, password, userAgent);
        //构建返回值
        ItripTokenVO tokenVO=new ItripTokenVO();
        tokenVO.setToken(token);
        //获取token生成时间
        String currentTime = token.split("-")[3];
        long cuttTime = new SimpleDateFormat("yyyyMMddHHssss").parse(currentTime).getTime();
        tokenVO.setGenTime(cuttTime);
        tokenVO.setExpTime(cuttTime+ Constants.RedisExpire.SESSION_TIMEOUT*1000);
        return DtoUtil.returnDataSuccess(tokenVO);
    }
    @ApiOperation(value ="注销")
    @GetMapping("/logout")
    public Dto logout(@ApiParam(value = "令牌") @RequestHeader( value = "token") String token,
                      @ApiParam(hidden = true) @RequestHeader( value = "user-agent") String userAgent
                      ) throws Exception
    {
        loginService.logout(token,userAgent);
        return DtoUtil.returnDataSuccess("注销成功");
    }
}
